from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from .models import User
from rest_framework import serializers


class UserSerializer(serializers.HyperlinkedModelSerializer):
    '''
    用户序列化器
    '''

    readable_gender = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ('url', 'username', 'password', 'gender', 'readable_gender', 'groups')

    # 存储用户密码时进行加密
    def create(self, validate_data):
        instance = super().create(validate_data)
        instance.set_password(validate_data['password'])
        instance.save()
        return instance

    # 密码加密处理
    def update(self, instance, validated_data):
        old_password = instance.password
        new_password = validated_data['password']
        instance = super().update(instance, validated_data)
        if (old_password != new_password):
            instance.set_password(validated_data['password'])
            instance.save()
        return instance

    def get_readable_gender(self, obj):
        return obj.get_gender_display()


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    # permissions = serializers.ListField(write_only=True)
    class Meta:
        model = Group
        # fields = ('url', 'name', 'permissions')
        fields = '__all__'


class PermissionSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Permission
        fields = ('url', 'name')
        # fields = '__all__'


class ContentTypeSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = ContentType
        fields = '__all__'
